﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZTool.Domain.DO;

namespace ZTool.Domain
{
    class DomainFactory
    {
        private RegistryCenter registryCenter = new RegistryCenter();

        #region Singleton
        private DomainFactory() { }
        private static readonly Lazy<DomainFactory> instance = new Lazy<DomainFactory>(() => new DomainFactory());
        public static DomainFactory Instance => instance.Value;
        #endregion

        #region Methods
        public Server CreateServer(string serviceName, string title, TimeDate now, Address address, Port port, ServerModel model)
        {
            Server server = new Server();

            server.SetName(serviceName);
            server.SetTitle(title);
            server.SetRegisterTime(now);
            server.SetUpdateTime(now);
            server.SetAddress(address);
            server.SetPort(port);
            server.SetModel(model);

            registryCenter.Register(serviceName, server);

            return server;
        }

        public bool ValidateServer(string name)
        {
            return !string.IsNullOrEmpty(name) && registryCenter.Contain(name);
        }
        public void HeartBeat(string name)
        {
            registryCenter.UpdateTime(name, TimeDate.of(DateTime.Now));
        }
        public ConcurrentDictionary<string, Server> GetServers()
        {
            return registryCenter.Services;
        }
        public Server GetServer(string name)
        {
            if (!registryCenter.Contain(name))
            {
                return null;
            }

            return registryCenter.Services[name];
        }

        #endregion
    }
}
